package com.boxfishedu.conf;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;

/**
 * Created by lzx on 16/7/6.
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.boxfishedu.primary", entityManagerFactoryRef = "primaryEntityManager",
        transactionManagerRef = "primaryTransactionManager")
@EnableTransactionManagement
public class PrimaryRepositoryConf {

    @Autowired
    @Qualifier(value = "primaryDataSource")
    DataSource primaryDataSource;

    @Autowired
    JpaProperties jpaProperties;

    /**
     * 生成实体管理器bean
     *
     * @param builder
     * @return
     */
    @Bean(name = "primaryEntityManager")
    public EntityManagerFactory entityManagerFactory(EntityManagerFactoryBuilder builder) {
        return localContainerEntityManagerFactoryBean(builder).getObject();
    }

    @Bean(name = "primaryEntityManagerFactoryBean")
    public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean =
                builder.dataSource(primaryDataSource)
                        .properties(jpaProperties.getHibernateProperties(primaryDataSource))
                        .packages("com.boxfishedu.primary")
                        .persistenceUnit("primaryPersistUnit")
                        .build();
        return localContainerEntityManagerFactoryBean;
    }

    @Bean(name = "primaryTransactionManager")
    public PlatformTransactionManager platformTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactory(builder));
    }

}
